package com.budwk.app.sqfwV2.generator.binyangStreet.excel;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfwDoc.bo.SqfwExcelForSummaryBO;
import com.budwk.app.sqfwDoc.bo.SqfwExcelJudgeRes;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseExcelParamDTO;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseTemplateExcelGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.SqfwExcelCreateCommonBO;
import com.budwk.app.sqfwV2.component.BinyangStreetComponent;
import com.budwk.app.sqfwV2.component.DayingRoadPdfComponent;
import com.budwk.app.sqfwV2.component.SignImageComponent;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskParamDataDTO;
import com.budwk.app.sqfwV2.dto.dto.centuryCity.SafeCheckTaskPdfDTO;
import com.budwk.app.sqfwV2.dto.image.ExcelProblemImageConfigBO;
import com.budwk.app.sqfwV2.enums.BinYangFileServiceEnum;
import com.budwk.app.sqfwV2.enums.RectificateTimeEnum;
import com.budwk.app.sqfwV2.enums.centuryCitySafe.EnterpriseSafetyProblemsEnum;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.excelPictureConfigBO.ExcelFileCreateParamBO;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 宾阳街道大型企业安全检查隐患清单
 * @since 2024-03-11
 */

@Slf4j
public class EnterpriseSafetyInvestigationExcel extends BaseTemplateExcelGenerator implements BinyangStreetExcelGenerator {

    @Override
    protected String getTemplateName() {
        return BinYangFileServiceEnum.TWO_EXCEL.getFilePath();
    }

    @Override
    public String getDownloadFileName() {
        return BinYangFileServiceEnum.TWO_EXCEL.getFileName();
    }

    /**
     * 用户自定义excel基础参数，比如表头这样的公用数据
     * @param excelParam 已经填充的基础数据据
     * @param excelCreateParam excel生成提供的原料
     */
    @Override
    protected void customerPopularSheetBaseParam(Map<String, Object> excelParam, SqfwExcelCreateCommonBO excelCreateParam) {
        log.info("EnterpriseSafetyInvestigationExcel getBaseExcelParamDTO: {}", JSONObject.toJSONString(excelCreateParam.getBaseExcelParamDTO()));
        BaseExcelParamDTO baseParam = excelCreateParam.getBaseExcelParamDTO();
        excelParam.put("county", StrUtil.formatStr(baseParam.getCounty()));
        excelParam.put("community", StrUtil.formatStr(baseParam.getCommunity()));
        excelParam.put("downloadDateStr", DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN));
    }

    /**
     * 构造内容体
     * @param listMap
     * @param excelCreateParam
     */
    @Override
    protected void customerPopularSheetDataParam(List<Map<String, Object>> listMap, SqfwExcelCreateCommonBO excelCreateParam) {
        List<Sqfw_formSummary_new> res = DayingRoadPdfComponent.getSummaryList(listMap, excelCreateParam);
        if (res.size() == 0) {
            return;
        }
        List<Sqfw_formSummary_new> summaryList = res.stream().sorted(Comparator.comparing(Sqfw_formSummary_new::getFillDate)).collect(Collectors.toList());
        log.info("EnterpriseSafetyInvestigationExcel summaryList:  {}", JSONObject.toJSONString(summaryList));
        List<Sqfw_formSummary_new> exportData = getExportData(summaryList);
        buildExcelMap(exportData, listMap);
        log.info("EnterpriseSafetyInvestigationExcel customerDataParam end: {}", JSONObject.toJSONString(listMap));
    }

    public List<Sqfw_formSummary_new> getExportData(List<Sqfw_formSummary_new> summaryList) {
        List<Sqfw_formSummary_new> datas = new ArrayList<>();
        for (Sqfw_formSummary_new summary : summaryList) {
            SafeCheckTaskPdfDTO roadPdfDTO = JSONObject.parseObject(summary.getParamData(), SafeCheckTaskPdfDTO.class);
            if (!isGenerateExcel(roadPdfDTO)) {
                continue;
            }
            //观山街道新增小区字段
            if (StringUtils.isNotBlank(roadPdfDTO.getPlot())) {
                String address = roadPdfDTO.getPlot();
                if (StringUtils.isNotBlank(roadPdfDTO.getAddress())) {
                    address = String.format("%s(%s)", roadPdfDTO.getPlot(), roadPdfDTO.getAddress());
                }
                roadPdfDTO.setAddress(address);
                summary.setParamData(JSONObject.toJSONString(roadPdfDTO));
            }

            datas.add(summary);
        }
        return datas;
    }

    public boolean isGenerateExcel(SafeCheckTaskPdfDTO pdfDTO) {
        return BinYangFileServiceEnum.TWO_EXCEL.getLabel().equals(pdfDTO.getType());
    }

    // 存在复查情况
    private void buildParamLessOne(Sqfw_formSummary_new summary, List<Map<String, Object>> listMap, SafeCheckTaskPdfDTO nextPdfDto, List<Sqfw_formSummary_new> datas) {
        SafeCheckTaskPdfDTO roadPdfDTO = JSONObject.parseObject(summary.getParamData(), SafeCheckTaskPdfDTO.class);
        // 2 问题集
        List<SafeCheckTaskParamDataDTO> problems = roadPdfDTO.getHiddenDanger();
        boolean isExistDanger = false; // 是否存在隐患
        List<SafeCheckTaskParamDataDTO> nextHidders = null;
        if (nextPdfDto != null) {
            nextHidders = nextPdfDto.getHiddenDanger(); // 复查的结果数据;
        }

        for (SafeCheckTaskParamDataDTO problem : problems) {
            EnterpriseSafetyProblemsEnum defaultEnum = EnterpriseSafetyProblemsEnum.getEnumByFields(problem.getFields());
            if (problem.getKey().equals(defaultEnum.getDefaultValue())) {
                continue;
            }
            // 1 基本信息
            Map<String, Object> map = BinyangStreetComponent.buildBaseExcelMap(roadPdfDTO, summary);
            isExistDanger = true;
            // 问题隐患
            map.put("problemDesc", StrUtil.replaceNullIsNo(problem.getNineSmallPlacesIssuesAndRisks()));
            // 隐患级别
            map.put("riskLevel", StrUtil.replaceNullIsNo(problem.getRiskLevel()));
            // 报告情况
            map.put("reportDesc", "已告知");
            // 处置情况 如果当前数据是立即整改
            map.put("disposal", getDisposal(problem, nextHidders, defaultEnum));
            // 隐患图片
            SignImageComponent.signExcel(map, 1, problem.getRiskImages(), "无", "riskImages", "riskImagesStr");
            // 整改后图片
            SignImageComponent.signExcel(map, 1, problem.getRectificationBackPhoto(), "无", "rectificationBackPhoto", "rectificationBackPhotoStr");
            listMap.add(map);
        }
        // 1 有隐患
        if (isExistDanger) {
            return;
        }
        // 2 没有隐患并且不属于复查数据
        if (StringUtils.isEmpty(roadPdfDTO.getLastSummaryId())) {
            BinyangStreetComponent.buildNullMap(listMap, roadPdfDTO, summary);
            return;
        }
        // 检查上一条数据是否有问题
        List<SafeCheckTaskParamDataDTO> defaultValues = EnterpriseSafetyProblemsEnum.getDefaultValues();
        if (!BinyangStreetComponent.checkLastExistIsDanger(roadPdfDTO.getLastSummaryId(), defaultValues)) {
            BinyangStreetComponent.buildNullMap(listMap, roadPdfDTO, summary);
            return;
        }
        // 判断上一次的数据是否在当前选中的数据中
        Optional<Sqfw_formSummary_new> optional = datas.stream().filter(e -> roadPdfDTO.getLastSummaryId().equals(e.getId())).findFirst();
        if (optional.isEmpty()) {
            BinyangStreetComponent.buildNullMap(listMap, roadPdfDTO, summary);
        }
    }



    private String getDisposal(SafeCheckTaskParamDataDTO problem, List<SafeCheckTaskParamDataDTO> nextHidders, EnterpriseSafetyProblemsEnum defaultEnum) {
        if (RectificateTimeEnum.IMMEDIATE_RECTIFICAIOTN.getCode().equals(problem.getRectificationTypeCode())) {
            return "已整改";
        }
        // 期限整改
        if (nextHidders != null) {
            SafeCheckTaskParamDataDTO nextSafe = nextHidders.stream().filter(e -> e.getFields().equals(problem.getFields())).findFirst().get();
            // 复查数据属于已整改
            if (defaultEnum.getDefaultValue().equals(nextSafe.getKey())) {
                return "已整改";
            }
        }
        return "整改中";
    }

    private void buildExcelMap(List<Sqfw_formSummary_new> datas, List<Map<String, Object>> listMap) {
        List<String> lastSummaryIds = datas.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList());
        SqfwFormsummaryNewService formsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
        // 查询下一次的数据 即复查数据
        List<Sqfw_formSummary_new> nextFormSummary = formsummaryNewService.queryByLastSummaryId(lastSummaryIds);
        for (Sqfw_formSummary_new summary : datas) {
            // 1 判断当前数据是否复查过并且不是复查数据
            SafeCheckTaskPdfDTO nextPdfDto = BinyangStreetComponent.getNextSafeCheckTaskPdfDTO(summary.getId(), nextFormSummary);
            buildParamLessOne(summary, listMap, nextPdfDto, datas);
        }
        // 赋值序号
        int num = 1;
        for (Map<String, Object> map : listMap) {
            map.put("num", num++);
        }
    }

    @Override
    protected void completeExcelFileCreateParam(ExcelFileCreateParamBO excelFileCreateParam) {

    }

    @Override
    protected void customerPopularRowDataMap(Map<String, Object> rowDataMap, SqfwExcelForSummaryBO forSummaryBO) {

    }

    @Override
    protected SqfwExcelJudgeRes judgeDataIntoExcelBeforeErgodic(SqfwExcelCreateCommonBO excelCreateParam, Map<String, Object> excelParam) {
        return null;
    }

    @Override
    protected SqfwExcelJudgeRes judgeDataIntoExcelBeforeCreate(Map<String, Object> excelParam) {
        return null;
    }

    @Override
    protected Class<?> getImageConfigBO() {
        return ExcelProblemImageConfigBO.class;
    }
}
